<template>
  <div class="order-container" v-if="!loadingStore.loading">
    <star-nav-bar ref="navBarRef" title="我的订单" />
    <van-tabs
      ref="tabsRef"
      sticky
      :offset-top="`${navBarHeight}px`"
      v-model:active="orderStatus"
      @click-tab="onClickTab"
    >
      <van-tab v-for="item in orderTabs" :key="item.type" :title="item.text" :name="item.type" class="order-tab">
        <div class="order-list-container">
          <van-pull-refresh v-model="pullLoading" @refresh="onRefresh" :disabled="pullDisabled">
            <van-list
              class="order-list"
              v-if="orderList.length !== 0"
              v-model:loading="loadLoading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
              @scroll="onScroll"
            >
              <div class="box order-item" v-for="item in orderList" :key="item.id" @click="onClickOrder(item.id)">
                <div class="title">
                  {{ item.businessName }}<span>{{ getOrderStatus(item.status) }}</span>
                </div>
                <div class="info"></div>
                <div class="oreder-time">
                  <span>{{ item.orderTime }}</span>
                </div>
              </div>
            </van-list>
            <star-empty v-else />
          </van-pull-refresh>
        </div>
      </van-tab>
    </van-tabs>
  </div>
  <star-loading v-else />
</template>
<script setup lang="ts">
import { getOrderListAPI } from '@/api/order'
import type { OrderDetailResult } from '@/types/order'
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getOrderStatus, orderTabs } from './constant'
import starNavBar from '@/components/star-nav-bar.vue'
import { showFailToast, type TabsInstance, type ListInstance } from 'vant'
import { useloadingStore } from '@/stores/modules/loading'
const loadingStore = useloadingStore()
const router = useRouter()
const route = useRoute()
// 导航栏
const navBarRef = ref<InstanceType<typeof starNavBar> | null>(null)
const navBarHeight = ref(0)
const tabsRef = ref<TabsInstance | null>(null)
// 初次数据加载状态
const isLoading = ref(true)
// 下拉刷新
const pullLoading = ref(false)
// 禁止下拉刷新
const pullDisabled = ref(false)
// 页面滚动加载
const loadLoading = ref(false)
// 是否全部加载完成
const finished = ref(false)
// 订单列表
const orderList = ref<OrderDetailResult[]>([])
// 页面路由参数订单状态
const orderStatus = ref(Number(route.query.tab) || 0)
// 订单列表查询
const page = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 更新导航栏高度的函数
const updateNavBarHeight = () => {
  if (navBarRef.value && navBarRef.value.$el) {
    navBarHeight.value = navBarRef.value.$el.offsetHeight
    // console.log(navBarHeight.value)
  } else {
    navBarHeight.value = 0
  }
}
// 重置数据
const resetOrderList = () => {
  orderList.value = []
  page.value = 1
  total.value = 0
  finished.value = false
}
// 下拉刷新
const onRefresh = async () => {
  isLoading.value = true
  pullLoading.value = true
  resetOrderList()
  try {
    await getOrderList()
    isLoading.value = false
    pullLoading.value = false
  } catch (e) {
    console.log(e)
    showFailToast('刷新失败,请重试')
  }
}

// 切换tab
const onClickTab = async (tab: { name: number }) => {
  // 更新 orderStatus
  orderStatus.value = tab.name
  // 更新 URL 查询参数以反映当前 tab
  if (route.query.tab !== tab.name.toString()) {
    resetOrderList()
    router.replace({
      path: route.path, // 保持当前路径不变
      query: { tab: tab.name }, // 更新查询参数
    })
    // 调用获取订单列表的函数
    await getOrderList()
  }
}

// 加载订单列表数据
const getOrderList = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    status: orderStatus.value === 0 ? undefined : +orderStatus.value,
  }
  try {
    const { data } = await getOrderListAPI(params)
    if (orderList.value.length === 0) {
      orderList.value = data.records
    } else {
      orderList.value = [...orderList.value, ...data.records]
    }
    total.value = data.total
    page.value += 1
    isLoading.value = false
    if (orderList.value.length >= total.value) {
      finished.value = true // 如果已加载的数据量等于总数据量，则设置加载完成
    }
  } catch (error) {
    console.log(error)
    isLoading.value = false
  }
}
// 加载更多数据
const onLoad = async () => {
  if (!finished.value) {
    await getOrderList()
    loadLoading.value = false
  }
}
// 监听列表滚动
const onScroll = (e: any) => {
  if (e.target.scrollTop === 0) {
    pullDisabled.value = false
  } else {
    pullDisabled.value = true
  }
}
// 跳转订单详情页
const onClickOrder = (id: number) => {
  router.push({ path: '/order/detail', query: { orderId: id } })
}

onMounted(async () => {
  loadingStore.showLoading()
  updateNavBarHeight()
  await getOrderList()
  await nextTick(() => {
    if (navBarRef.value) {
      window.addEventListener('resize', updateNavBarHeight)
    }
  })
  loadingStore.hideLoading()
})
onUnmounted(() => {
  if (navBarRef.value) {
    window.removeEventListener('resize', updateNavBarHeight)
  }
})
</script>
<style scoped lang="scss">
:deep() {
  .van-tabs__nav {
    background: var(--gray-background); // 确保 tab 栏在滚动时固定
    position: sticky;
    top: 0;
    z-index: 10; // 确保它位于其他内容之上
  }
  // .van-sticky--fixed {
  //   transition: all 0.5s ease-in-out;
  // }
}
.order-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  box-sizing: border-box;
  overflow: hidden;
}
.van-tabs {
  flex: 1;
  background: var(--gray-background);
}
.order-list-container {
  height: calc(100vh - 2 * var(--nav-bar-height) - 10px);
  overflow: hidden;
  margin: 10px 0;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
.order-list {
  flex: 1;
  height: calc(100vh - 2 * var(--nav-bar-height) - 10px);
  overflow-y: auto;
}
.order-item {
  padding: 10px;
  min-height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .title {
    display: flex;
    justify-content: space-between;
    span {
      font-size: 14px;
      font-weight: normal;
      color: #999;
    }
  }
}
</style>
